import sys
import os
import gradio as gr

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from .utils import ArgumentParser, LOG
from .translator import PDFTranslator, TranslationConfig


def translation(input_file, output_file_format, source_language, target_language, start_page=0, end_page=None):
    LOG.debug(f"[翻译任务]\n源文件: {input_file.name}\n源语言: {source_language}\n目标语言: {target_language}")

    output_file_path = Translator.translate_pdf(
        input_file.name, output_file_format=output_file_format, source_language=source_language, target_language=target_language, start_page=int(start_page),
        end_page=int(end_page) if end_page else None
    )

    return output_file_path


def launch_gradio():
    iface = gr.Interface(
        fn=translation,
        title="OpenAI PDF 翻译器 V2.0",
        inputs=[gr.File(label="上传PDF文件"),
                gr.Textbox(label="输出文件格式", value="markdown", placeholder="支持 PDF 和 Markdown 格式"),
                gr.Textbox(label="源语言", value="English", placeholder="请输入源语言"),
                gr.Textbox(label="目标语言", value="Chinese", placeholder="请输入目标语言"),
                gr.Textbox(label="翻译起始页码", value="0", placeholder="请输入目标语言"),
                gr.Textbox(label="翻译终止页码", value="", placeholder="请输入目标语言")],
        outputs=gr.File(label="下载翻译文件"),
        allow_flagging="never")
    iface.launch(share=True, server_name="0.0.0.0")


def initialize_translator():
    argument_parser = ArgumentParser()
    args = argument_parser.parse_arguments()

    config = TranslationConfig()
    config.initialize(args)

    global Translator
    Translator = PDFTranslator(config.model_name)


if __name__ == "__main__":
    initialize_translator()
    LOG.info("翻译器初始化完成，开始启动 Gradio 服务器...")
    launch_gradio()
    LOG.info("Gradio 服务器已启动，等待用户上传文件进行翻译。")
